import { useState, useEffect } from 'react';
import { Upload, Image, message, Modal, Form, Input } from 'antd';
import styled from "@emotion/styled";
import { Icon } from '../form-generator/icon';

const utf8encode = (str) => {
    const string = str.replace(/\r\n/g, "\n");
    var utftext = "";
    for (var n = 0; n < string.length; n++) {
        var c = string.charCodeAt(n);
        if (c < 128) {
            utftext += String.fromCharCode(c);
        } else if ((c > 127) && (c < 2048)) {
            utftext += String.fromCharCode((c >> 6) | 192);
            utftext += String.fromCharCode((c & 63) | 128);
        } else {
            utftext += String.fromCharCode((c >> 12) | 224);
            utftext += String.fromCharCode(((c >> 6) & 63) | 128);
            utftext += String.fromCharCode((c & 63) | 128);
        }
    }
    return utftext;
}
const base64Encode = (input) => {
    const _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    let output = "";
    let chr1, chr2, chr3, enc1, enc2, enc3, enc4;
    let i = 0;
    input = utf8encode(input);
    while (i < input.length) {
        chr1 = input.charCodeAt(i++);
        chr2 = input.charCodeAt(i++);
        chr3 = input.charCodeAt(i++);
        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;
        if (isNaN(chr2)) {
            enc3 = enc4 = 64;
        } else if (isNaN(chr3)) {
            enc4 = 64;
        }
        output = output +
            _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
            _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
    }
    return output
}

// 上传图片生成印章
export const Stamp = ({ value, onChange, ...rest }) => {
    const [base64, setBase64] = useState('');

    useEffect(() => {
        if (value) {
            const [imgSrc] = value.split('.');
            setBase64(imgSrc);
        } else {
            setBase64('');
        }
    }, [value]);

    const [form] = Form.useForm();

    const beforeUpload = async (file) => {
        // 图片大小限制
        const fileSizeLimit = 1024 * 1024;
        if (file.size > fileSizeLimit) {
            message.error(`图片大小超过限制，最大支持1M`);
            return Upload.LIST_IGNORE;
        }

        const password = await setPassword();

        const src = await blob2base64(file);
        onChange && onChange(`${src}.${base64Encode(password)}`);

        return false;
    }

    // 设置印章密码
    const setPassword = () => new Promise((resolve, reject) => {
        Modal.confirm({
            title: '设置密码',
            content: (
                <Form form={form}>
                    <Form.Item
                        name="password"
                        rules={[{
                            required: true,
                            message: '请输入印章使用密码'
                        }, {
                            min: 4,
                            message: '密码不能少于4个字符'
                        }, {
                            max: 20,
                            message: '密码不能超过20个字符'
                        }]}
                        style={{ marginBottom: 0 }}
                    >
                        <Input.Password maxLength={20} placeholder="请输入印章使用密码" />
                    </Form.Item>
                </Form>
            ),
            onOk: async () => {
                const vals = await form.validateFields();
                resolve(vals.password);
            }
        });
    });

    // Blob图片转base64用于预览
    const blob2base64 = (file) => new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.addEventListener('load', () => {
            resolve(reader.result);
        });
        reader.readAsDataURL(file);
    });

    return (
        <Container>
            {
                rest.readonly ? (
                    <Image className="img" src={base64} alt="印章" />
                ) : (
                    <Upload
                        accept="image/*"
                        beforeUpload={beforeUpload}
                        showUploadList={false}
                        disabled={rest.disabled}
                    >
                        {
                            base64 ? (
                                <img className="img" src={base64} alt="印章" />
                            ) : (
                                <div className="placeholder">
                                    <Icon className="icon" type="stamp" />
                                    <div className="holder-text">添加印章</div>
                                </div>
                            )
                        }

                    </Upload>
                )
            }
        </Container>
    );
}

const Container = styled.div`
    .img {
        width: 72px;
        height: 72px;
    }
    .placeholder {
        color: #666;
        border: 1px dashed #ccc;
        width: 72px;
        height: 72px;
        text-align: center;
        cursor: pointer;
        & > .icon {
            margin-top: 16px;
        }
        & > .holder-text {
            font-size: 12px;
        }
    }
`
